import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'

function Square(props) {
  return (
    <button
      className={`square ${props.arrange.includes(props.id) ? 'active' : ''}`}
      onClick={props.onClick}
    >
      {props.value}
    </button>
  )
}

class Board extends React.Component {
  renderSquare(i) {
    return (
      <Square
        key={i}
        id={i}
        arrange={this.props.arrange}
        value={this.props.squares[i]}
        onClick={() => this.props.onClick(i)}
      />
    )
  }

  isInArrange(array, key) {
    return array.includes(key)
  }

  render() {
    return (
      <div>
        {Array(3)
          .fill(null)
          .map((item, i) => (
            <div className="board-row" key={i}>
              {Array(3)
                .fill(null)
                .map((item, j) => this.renderSquare(i > 0 ? i * 3 + j : j))}
            </div>
          ))}
      </div>
    )
  }
}

class Game extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      history: [
        {
          squares: Array(9).fill(null).slice(),
        },
      ],
      stepNumber: 0,
      xIsNext: true,
      msgHistory: [''], //落子坐标记录数组
    }
  }

  handleClick(i) {
    const history = this.state.history.slice(0, this.state.stepNumber + 1)
    const current = history[history.length - 1]
    const squares = current.squares.slice()
    const msgHistory = this.state.msgHistory.slice(0, this.state.stepNumber + 1)
    let msg = []
    if (i < 3) {
      msg.push(`当前落子坐标：列${i + 1}行${1}`)
    } else if (i < 6) {
      msg.push(`当前落子坐标：列${(i % 3) + 1}行${2}`)
    } else {
      msg.push(`当前落子坐标：列${(i % 3) + 1}行${3}`)
    }

    //有人赢或者格子被占用
    if (calculateWinner(squares).win || squares[i]) {
      return
    }
    squares[i] = this.state.xIsNext ? 'X' : 'O'
    this.setState({
      history: history.concat([
        {
          squares: squares,
        },
      ]),
      stepNumber: history.length,
      xIsNext: !this.state.xIsNext,
      msgHistory: msgHistory.concat(msg),
    })
  }

  jumpTo(step) {
    this.setState({
      stepNumber: step,
      xIsNext: step % 2 === 0,
    })
  }

  render() {
    const history = this.state.history
    const current = history[this.state.stepNumber]
    const result = calculateWinner(current.squares)
    const moves = history.map((step, move) => {
      //第二步才出现跳转步骤按钮， move是索引
      const desc = move ? 'Go to move #' + move : 'Go to game start'
      return (
        <li key={move}>
          <button
            className={move === this.state.stepNumber ? 'btn' : ''}
            onClick={() => this.jumpTo(move)}
          >
            {desc}
          </button>
        </li>
      )
    })

    let status
    let arrange = []
    if (result.win) {
      status = `胜出者为：${result.winner}`
      // console.log(result)
      arrange = result.arrange
    } else {
      if (
        current.squares.every((item) => {
          return item !== null && item !== ''
        })
      ) {
        status = '平局！'
      } else {
        status = 'Next player:' + (this.state.xIsNext ? 'X' : 'O')
      }
    }
    return (
      <div className="game">
        <div className="game-board">
          <Board arrange={arrange} squares={current.squares} onClick={(i) => this.handleClick(i)} />
        </div>
        <div className="game-info">
          <div>{status}</div>
          <div>{this.state.msgHistory[this.state.stepNumber]}</div>
          <ol>{moves}</ol>
        </div>
      </div>
    )
  }
}

//计算胜者
function calculateWinner(squares) {
  //胜利的情况
  const lines = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
  ]
  //循环判断，相同的三子符合数组里的某一项就是胜利
  for (let i = 0; i < lines.length; i++) {
    const [a, b, c] = lines[i]
    if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
      return {
        win: true,
        winner: squares[a],
        arrange: lines[i],
      }
    }
  }
  return {
    win: false,
    winner: null,
    arrange: [],
  }
}

// ========================================

ReactDOM.render(<Game />, document.getElementById('root'))
